//
//  DefineMacro.swift
//  ThinkerRide
//
//  Created by sqkj on 2021/3/11.
//  Copyright © 2021 Chongqing Thinkerride Technology Co., Ltd. All rights reserved.
//

import Foundation
import UIKit

//状态栏高度
public var Status_Bar_Height:CGFloat {
    if #available(iOS 11.0, *) {
        guard let keyWindow = UIApplication.shared.keyWindow else { return 20.0 }
        return keyWindow.safeAreaInsets.top == 0 ? 20 : keyWindow.safeAreaInsets.top
    }else{
        return 20.0
    }
}

//导航栏的高度
public let Navigation_Bar_Height:CGFloat = 44.0

//状态栏+导航栏高度
public let Status_And_Navigation_Height = Status_Bar_Height + Navigation_Bar_Height

//TabBar高度
public let TabBar_Height :CGFloat = 49.0

//底部安全区域高度34.0f
public var Bottom_Safe_Height:CGFloat {
    if #available(iOS 11.0, *) {
        guard let keyWindow = UIApplication.shared.keyWindow else { return 0.0 }
        return keyWindow.safeAreaInsets.bottom
    }else{
        return 0.0
    }
}

//TabBar+安全区域高度
public let TabBar_And_Bottom_Safe_Height = Bottom_Safe_Height + TabBar_Height


//屏幕宽高
public let KScreenWidth = UIScreen.main.bounds.size.width
public let KScreenHeight = UIScreen.main.bounds.size.height


//设备屏幕适配计算，用于SnapKit布局，frame布局页面，%百分比适配布局比例计算
public let RatioWidth750 = UIScreen.main.bounds.size.width / 375.0
public let RatioHeigth750 = (UIScreen.main.bounds.size.width - Status_And_Navigation_Height - TabBar_And_Bottom_Safe_Height) / (667.0 - 64 - 49)

//状态栏颜色
public class GlobalFunction {
    
    public static func setStatusBarLightContent(isNeedLight: Bool) {
        let application = UIApplication.shared
        
        if isNeedLight {
            if application.statusBarStyle == .default {
                application.statusBarStyle = .lightContent
            }
        }else{
            if application.statusBarStyle == .lightContent {
                application.statusBarStyle = .default
            }
        }
    }
}

// 颜色
//十六进制颜色
public extension UIColor {
 
    //十六进制颜色
    static func RGBColorHex(_ rgb: UInt64) -> UIColor {
        return UIColor(red: CGFloat(((rgb>>16)&0xFF))/255.0, green: CGFloat(((rgb>>8)&0xFF))/255.0, blue: CGFloat((rgb&0xFF))/255.0, alpha: 1.0)
    }
    
    //RGBA颜色
    static func RGBAColor(r: CGFloat, g: CGFloat, b: CGFloat, a:CGFloat) -> UIColor {
        return UIColor(red: CGFloat(r) / 255.0,
                       green: CGFloat(g) / 255.0,
                       blue: CGFloat(b) / 255.0,
                       alpha: CGFloat(a))
    }
    
    //RGBA颜色
    static func rgba(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a:CGFloat) -> UIColor {
        return UIColor(red: CGFloat(r) / 255.0,
                       green: CGFloat(g) / 255.0,
                       blue: CGFloat(b) / 255.0,
                       alpha: CGFloat(a))
    }
    
    //随机颜色
    func RandomColor() -> UIColor {
        let red = CGFloat(arc4random()%256)/255.0
        let green = CGFloat(arc4random()%256)/255.0
        let blue = CGFloat(arc4random()%256)/255.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
    
}

public func kRGBAColor(_ r: CGFloat,_ g: CGFloat,_ b: CGFloat,_ a: CGFloat) -> UIColor {
    return UIColor.init(red: r, green: g, blue: b, alpha: a)
}
public func kRGBColor(_ r: CGFloat,_ g: CGFloat,_ b: CGFloat) -> UIColor {
    return UIColor.init(red: r, green: g, blue: b, alpha: 1.0)
}

public let kColor_nil = UIColor.clear

// UserDefaults
public let kUserDefaults = UserDefaults.standard
public func kUserDefaultsRead(_ KeyStr: String) -> String {
    return kUserDefaults.string(forKey: KeyStr)!
}
public func kUserDefaultsWrite(_ obj: Any, _ KeyStr: String) {
    kUserDefaults.set(obj, forKey: KeyStr)
}
public func kUserValue(_ A: String) -> Any? {
    return kUserDefaults.value(forKey: A)
}
public func DPrint(_ item: @autoclosure () -> Any) {
    #if DEBUG
    print(item())
    #endif
}

//开发的时候打印，但是发布的时候不打印,使用方法，输入print(message: "输入")
public func print<T>(message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line) {
    #if DEBUG
    //获取当前时间
    let now = Date()
    // 创建一个日期格式器
    let dformatter = DateFormatter()
    dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
    // 要把路径最后的字符串截取出来
    let lastName = ((fileName as NSString).pathComponents.last!)
    DPrint("\(dformatter.string(from: now)) [\(lastName)][第\(lineNumber)行] \n\t\t \(message)")
    #endif
}

//获取屏幕大小
public let kUIScreenSize = UIScreen.main.responds(to: #selector(getter: UIScreen.nativeBounds)) ? CGSize(width: UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale, height: UIScreen.main.nativeBounds.size.height / UIScreen.main.nativeScale) : UIScreen.main.bounds.size
public let kUIScreenWidth = kUIScreenSize.width
public let kUIScreenHeight = kUIScreenSize.height
public let kUIScreenBounds = UIScreen.main.bounds


//读取xib
public func kLoadNibNamed(_ name:String) -> [Any]?{
    return  Bundle.main.loadNibNamed(name, owner: nil, options: nil)![0] as? [Any]
}

//APP版本号
public let kAppVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
//当前系统版本号
public let kVersion = (UIDevice.current.systemVersion as NSString).floatValue
//检测用户版本号
public let kiOS12 = (kVersion >= 12.0)
public let kiOS11 = (kVersion >= 11.0 && kVersion < 12.0)
public let kiOS10 = (kVersion >= 10.0 && kVersion < 11.0)
public let kiOS9 = (kVersion >= 9.0 && kVersion < 10.0)
public let kiOS8 = (kVersion >= 8.0 && kVersion < 9.0)
public let kiOS12Later = (kVersion >= 12.0)
public let kiOS11Later = (kVersion >= 11.0)
public let kiOS10Later = (kVersion >= 10.0)
public let kiOS9Later = (kVersion >= 9.0)
public let kiOS8Later = (kVersion >= 8.0)

//获取当前语言
public let kAppCurrentLanguage = Locale.preferredLanguages[0]
//判断是否为iPhone
public let kDeviceIsiPhone = (UIDevice.current.userInterfaceIdiom == .phone)
//判断是否为iPad
public let kDeviceIsiPad = (UIDevice.current.userInterfaceIdiom == .pad)

//判断 iPhone 的屏幕尺寸
public let kSCREEN_MAX_LENGTH = max(kUIScreenWidth, kUIScreenHeight)
public let kSCREEN_MIN_LENGTH = min(kUIScreenWidth, kUIScreenHeight)

//适配 350 375 414       568 667 736
func kAutoLayoutWidth(_ width: CGFloat) -> CGFloat {
    return width*kUIScreenWidth / 375
}
func kAutoLayoutHeigth(_ height: CGFloat) -> CGFloat {
    return height*kUIScreenHeight / 667
}

//机型判断
public let kUI_IPHONE = (UIDevice.current.userInterfaceIdiom == .phone)
public let kUI_IPHONE5 = (kUI_IPHONE && kSCREEN_MAX_LENGTH == 568.0)
public let kUI_IPHONE6 = (kUI_IPHONE && kSCREEN_MAX_LENGTH == 667.0)
public let kUI_IPHONEPLUS = (kUI_IPHONE && kSCREEN_MAX_LENGTH == 736.0)
public let kUI_IPHONEX = (kUI_IPHONE && kSCREEN_MAX_LENGTH > 780.0)

//获取状态栏、标题栏、导航栏高度
public let kUIStatusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
public let kUINavigationBarHeight: CGFloat =  kUI_IPHONEX ? 88 : 44
public let KUITabBarHeight: CGFloat = kUI_IPHONEX ? 83 : 49
//navigationBarHeight默认高度44 （iPhoneX 88）
//tabBarHeight默认高度49     （iPhoneX 83）

///判断当前手机是否刘海屏
func isiPhoneX() -> Bool {
    guard #available(iOS 11.0, *) else {
        return false
    }
    
    let isResult = (UIApplication.shared.keyWindow?.safeAreaInsets.bottom)! > 0
    return isResult
}

// 注册通知
public func kNOTIFY_ADD(observer: Any, selector: Selector, name: String,object: Any?) {
    return NotificationCenter.default.addObserver(observer, selector: selector, name: Notification.Name(rawValue: name), object: object)
}
// 发送通知
public func kNOTIFY_POST(name: String, object: Any?) {
    return NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object)
}
// 发送通知带参数
public func kNOTIFY_POST_PARAM(name: String, object: Any?,userInfo:[AnyHashable : Any]? = nil) {
    return NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object,userInfo: userInfo)
}
// 移除通知
public func kNOTIFY_REMOVE(observer: Any, name: String, object: Any?) {
    return NotificationCenter.default.removeObserver(observer, name: Notification.Name(rawValue: name), object: object)
}

//代码缩写
public let kApplication = UIApplication.shared
public let kAPPKeyWindow = kApplication.keyWindow
public let kAppDelegate = kApplication.delegate
public let kAppNotificationCenter = NotificationCenter.default
public let kAppRootViewController = kAppDelegate?.window??.rootViewController

//字体 字号
public func kFontSize(_ a: CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: a)
}
public func kFontBoldSize(_ a: CGFloat) -> UIFont {
    return UIFont.boldSystemFont(ofSize: a)
}
public func kFontForIPhone5or6Size(_ a: CGFloat, _ b: CGFloat) -> UIFont {
    return kUI_IPHONE5 ? kFontSize(a) : kFontSize(b)
}

public func compareVersion(newVersion:String) -> Bool {
    let nowVersion:String = "2.0.0"
    let nowArray = nowVersion.split(separator: ".")
    let newArray = newVersion.split(separator: ".")
    let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
    for index in 0...big - 1 {
        let first = nowArray[index]
        let second = newArray[index]
        if Int(first)! < Int(second)!  {
            return true
        }
    }
    return false
}


//获取沙盒Document路径
public let kDocumentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
//获取沙盒Cache路径
public let kCachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
//获取沙盒temp路径
public let kTempPath = NSTemporaryDirectory()


/**
 字符串是否为空
 @param str NSString 类型 和 子类
 @return  BOOL类型 true or false
 */
public func kStringIsEmpty(_ str: String!) -> Bool {
    if str.isEmpty {
        return true
    }
    if str == nil {
        return true
    }
    if str.count < 1 {
        return true
    }
    if str == "(null)" {
        return true
    }
    if str == "null" {
        return true
    }
    return false
}
// 字符串判空 如果为空返回@“”
public func kStringNullToempty(_ str: String) -> String {
    let resutl = kStringIsEmpty(str) ? "" : str
    return resutl
}
public func kStringNullToReplaceStr(_ str: String,_ replaceStr: String) -> String {
    let resutl = kStringIsEmpty(str) ? replaceStr : str
    return resutl
}

/**
 数组是否为空
 @param array NSArray 类型 和 子类
 @return BOOL类型 true or false
 */
public func kArrayIsEmpty(_ array: [String]) -> Bool {
    let str: String! = array.joined(separator: "")
    if str == nil {
        return true
    }
    if str == "(null)" {
        return true
    }
    if array.count == 0 {
        return true
    }
    if array.isEmpty {
        return true
    }
    return false
}
/**
 字典是否为空
 @param dic NSDictionary 类型 和子类
 @return BOOL类型 true or false
 */
public func kDictIsEmpty(_ dict: NSDictionary) -> Bool {
    let str: String! = "\(dict)"
    if str == nil {
        return true
    }
    if str == "(null)" {
        return true
    }
    if dict .isKind(of: NSNull.self) {
        return true
    }
    if dict.allKeys.count == 0 {
        return true
    }
    return false
}


/**宽度比例*/
public func ScaleWidth(_ font:CGFloat) -> (CGFloat) {
   return (UIScreen.main.bounds.size.width/375)*font
}

/**高度比例*/
public func ScaleHeight(_ font:CGFloat) -> (CGFloat) {
  return  (UIScreen.main.bounds.size.height/667)*font
}
